﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WIA;
using System.Drawing;
using System.IO.IsolatedStorage;
using System.IO;
using System.Diagnostics;

namespace ImageAcquisitionTAL
{
    public class WIA20Technology : IAcquisitionTechnology
    {
        private Dictionary<string, DeviceInfo> installedDevices = new Dictionary<string, DeviceInfo>();

        public IEnumerable<Scanner> GetInstalledScanners()
        {
            List<Scanner> devs = new List<Scanner>();
            DeviceManager wiaManager = new DeviceManagerClass();            
            foreach (DeviceInfo di in wiaManager.DeviceInfos)
            {
                installedDevices.Add(di.DeviceID, di);
                Scanner s = new Scanner();
                s.DeviceID = di.DeviceID;
                s.DisplayName = GetDeviceName(di);
                devs.Add(s);
            }
            return devs;
        }

        private string GetDeviceName(DeviceInfo di)
        {
            return GetProp(di, "Name") + " (" + GetProp(di, "Description") + ")";
        }

        public Scanner GetScanner(string deviceId)
        {
            DeviceInfo d = GetDevice(deviceId);
            Scanner s = new Scanner();
            if (d == null)
                return s;
            s.DeviceID = deviceId;
            s.DisplayName = GetDeviceName(d);
            return s;
        }

        private DeviceInfo GetDevice(string id)
        {
            if (installedDevices.ContainsKey(id))
                return installedDevices[id];
            else
                return null;
        }

        private string GetProp(DeviceInfo info, string name)
        {
            foreach (Property p in info.Properties)
                if (p.Name == name)
                    return p.get_Value().ToString();
            return null;
        }

        public bool IsAvailable()
        {
            try
            {
                DeviceManager wiaManager = new DeviceManagerClass();
                wiaManager = null;
            }
            catch
            {
                return false;
            }
            return true;
        }

        public Image Acquire(string deviceId)
        {
            DeviceInfo di = GetDevice(deviceId);
            Device d = di.Connect();            
            Item item = d.Items[1];
            
            ImageFile file = item.Transfer(FormatID.wiaFormatTIFF) as ImageFile;
            string fileName = Path.Combine(Path.GetTempPath(), "HomeDMS.TMP." + Process.GetCurrentProcess().Id.ToString() + ".tiff");
            file.SaveFile(fileName);
            file = null;
            Image result = Image.FromFile(fileName);
            //File.Delete(fileName);
            return result;
        }
    }
}
